import os, sys
import  wx
import  wx.lib.mixins.listctrl  as  listmix


APPLICATION_INSTALL_DIR = os.environ.get('SIMPLEWATCHER_INSTALL')
if not APPLICATION_INSTALL_DIR:
    raise EnvironmentError("must set environment variable SIMPLEWATCHER_INSTALL")
sys.path.append('%s/lib' % APPLICATION_INSTALL_DIR)

from watch_builder.gui import utils
from watch_builder.gui.evthandle import registrar
from watch_builder.builder import buildKlass
from watcher.config import ConfigLoader

class WatcherObjectLister(wx.ListCtrl, listmix.ListCtrlAutoWidthMixin):
    def __init__(self, parent, ID, pos=wx.DefaultPosition, size=(125, 300), style=0):
        wx.ListCtrl.__init__(self, parent, ID, pos, size, style)
        listmix.ListCtrlAutoWidthMixin.__init__(self)
        

class WatcherObjectListerPanel(wx.Panel):
    def __init__(self, parent, id=-1, **kwargs):
        wx.Panel.__init__(self, parent, id, style=wx.WANTS_CHARS, **kwargs)
        self.config = ConfigLoader(os.path.join(APPLICATION_INSTALL_DIR, "lib%swatch_builder%sgui%sconfig" %(os.sep, os.sep, os.sep))).load("watcher_objects")
        self.list = WatcherObjectLister(self, -1, style=wx.LC_REPORT | wx.BORDER_NONE | wx.LC_EDIT_LABELS | wx.LC_SORT_ASCENDING)
        self.buildImageList()
        self.buildItemDataMap()
        self.PopulateList()
        self.registerEvents()
        # set current item to 0
        self.currentItem = 0
        self.currentItemData = {}
        self.dragInProgress = False
    
    
    def buildImageList(self):
        self.imageOrder = {}
        self.il = wx.ImageList(16, 16)
        count = 0
        for image in self.config.xml_xpath("//image_file"):
            self.imageOrder[str(image)] = count
            self.il.Add(utils.wxImageBuilder(str(image)))
            count += 1
        self.list.SetImageList(self.il, wx.IMAGE_LIST_NORMAL)


    def buildItemDataMap(self):
        idm = {}
        for obj in self.config.xml_xpath("//object"):
           idm[int(str(obj.list_order))] = [str(obj.display_name), str(obj.package), str(obj.klass), str(obj.image_file)]
        self.itemDataMap = idm


    def getListItemData(self, item):
        key = self.list.GetItemData(item)
        data = self.itemDataMap[key]
        return data
    
    
    def registerEvents(self):
        registrar.register(self.OnItemSelected, wx.EVT_LIST_ITEM_SELECTED, self.list)
        registrar.register(self.OnMotion, wx.EVT_MOTION, self.list)
    
    
    def buildDropSource(self, data):
        watcher_obj = buildKlass(data[1], data[2])(packageName=data[1], klass=data[2])
        watcher_obj.setObject(watcher_obj.guiObjXml())
        drop_source = wx.DropSource(self)
        drop_source.SetData(watcher_obj)
        return drop_source
        
    
    def OnItemSelected(self, event):
        self.currentItem = event.m_itemIndex
        data = self.getListItemData(self.currentItem)
        if not data == self.currentItemData:
            self.currentItemData = data


    def OnMotion(self, event):
        if not self.dragInProgress and event.Dragging():
            self.dragInProgress = True
            self.startDragDrop()

    def startDragDrop(self):
        drop_source = self.buildDropSource(self.currentItemData)
        result = drop_source.DoDragDrop(wx.Drag_CopyOnly)
        self.dragInProgress = False
        if result == wx.DragCopy:
            self.Refresh()
        


    def PopulateList(self):
        info = wx.ListItem()
        info.m_mask = wx.LIST_MASK_TEXT | wx.LIST_MASK_IMAGE | wx.LIST_MASK_FORMAT | wx.LIST_AUTOSIZE_USEHEADER
        info.m_image = -1
        info.m_format = 0
        info.m_text = "WatcherObjects"
        self.list.InsertColumnInfo(0, info)

        for key, data in self.itemDataMap.items():
            index = self.list.InsertImageStringItem(self.imageOrder[data[3]], data[0], self.imageOrder[data[3]])
            self.list.SetItemData(index, key)
        
        self.list.SetColumnWidth(0, wx.LIST_AUTOSIZE)
        self.currentItem = 0